package com.example.spring.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.example.spring.model.Role;

@Service("customUserDetailService")
@Transactional(readOnly = true)
public class CustomUserDetailService implements UserDetailsService{

	@Autowired
	UserService userService;
	
	@SuppressWarnings("unchecked")
	@Override
	public UserDetails loadUserByUsername(String username)throws UsernameNotFoundException {
		List<com.example.spring.model.User> userList = userService.getUser(username);
		com.example.spring.model.User user = userList.get(0);
		
		boolean enabled = true;  
        boolean accountNonExpired = true;  
        boolean credentialsNonExpired = true;  
        boolean accountNonLocked = true; 
        
        
        return new User(  
        		user.getUserName(),   
        		user.getPassword(),   
                enabled,   
                accountNonExpired,   
                credentialsNonExpired,   
                accountNonLocked,  
                getAuthorities(user.getRole())  
        ); 
	}

	@SuppressWarnings("rawtypes")
	public Collection getAuthorities(List<Role> role) {  
        List<GrantedAuthority> authList = getGrantedAuthorities(getRoles(role));  
        return authList;  
    }
	
	public List<String> getRoles(List<Role> role) {  
		  
        List<String> roles = new ArrayList<String>();  
  
        for(int i = 0 ; i < role.size() ; i++){
        	if (role.get(i).getId() == 1) {  
                roles.add("ROLE_ADMIN");  
            } 
        	if (role.get(i).getId() == 2) {  
                roles.add("ROLE_USER");  
            }
        }
          
        return roles;  
    }  
	
	public static List<GrantedAuthority> getGrantedAuthorities(List<String> roles) {  
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();  
          
        for (String role : roles) {  
            authorities.add(new SimpleGrantedAuthority(role));  
        }  
        return authorities;  
    } 
}
